from Accounting.Entity.Master import *
from Common.Singleton import Singleton 
from DataAccess.DBConnFactory import DBConnFactory
#import timeit

class EntityTree(Singleton):
	
	#def init_only_once(cls):
	def init_only_once(self):
		#start = timeit.default_timer()
		#print "invoke EntityTree::init_only_once()"
		cursor = DBConnFactory().get_db_connection('ACCOUNTING').cursor()

		sql_text = '''select distinct master_id from master_info'''
		cursor.execute(sql_text)
		r = cursor.fetchall()
		
		self.tree_root = {}  #self.children_roster
		for item in r:
			master_id = item[0]
			tmp = Master(master_id)
			tmp.create_children()
			
			self.tree_root[master_id] = tmp
		
	
	def find_node(self, id):
		if id in self.tree_root:
			return self.tree_root[id]

		for item in self.tree_root.values():
			tmp = item.find_child(id)
			if tmp:
				return tmp
					
		return None
		

	def get_root_nodes(self):
		return self.tree_root.values()